package com.chj.comp.common.auth.security.service;

import com.alibaba.fastjson.JSON;
import com.chj.comp.common.auth.entity.SysPermission;
import com.chj.comp.common.auth.entity.SysRole;
import com.chj.comp.common.auth.entity.SysUser;
import com.chj.comp.common.auth.service.ISysPermissionService;
import com.chj.comp.common.auth.service.ISysRoleService;
import com.chj.comp.common.auth.service.ISysUserService;
import com.chj.comp.common.core.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 使用UserDetailsService改变用户信息来源
 * @Author: cuihui
 */
@Service
@Slf4j
public class SecurityUserDetailService implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysPermissionService sysPermissionService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        log.info("-----loadUserByUsername-----");
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        SysUser user = sysUserService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //身份令牌
        String principal = JSON.toJSONString(user);
        List<String> authCodes = new ArrayList<>();
        //获取用户角色（角色必须以ROLE_开头，否则@PreAuthorize("hasRole('xx')")注解不生效）
        List<SysRole> roles = sysRoleService.getRolesByUserId(user.getId());
        if(CollectionUtils.isNotEmpty(roles)){
            List<String> rolesCodes = roles.stream().map(role -> {
                return CommonConstant.ROLE + role.getRoleCode();
            }).collect(Collectors.toList());
            authCodes.addAll(rolesCodes);
        }
        //获取用户权限
        List<SysPermission> permissions = sysPermissionService.getPermissionsByUserId(user.getId());
        if(CollectionUtils.isNotEmpty(permissions)){
            List<String> permCodes = permissions.stream().map(SysPermission::getPermCode).collect(Collectors.toList());
            authCodes.addAll(permCodes);
        }
        if(CollectionUtils.isNotEmpty(authCodes)){
            String[] authorities = authCodes.toArray(new String[authCodes.size()]);
            return User.withUsername(principal).password(user.getPassword()).authorities(authorities).build();
        }

        return User.withUsername(principal).password(user.getPassword()).authorities(new String[0]).build();
    }
}
